Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

235
Visualizações
HTML element "top" style being set generated random number but not moving to the position in JavaScript

I have been working on a project and remaking snake. The code is all supposed to set the position of the apple to a random number and it logs it as doing so, but the apple stays in the same place. The position type is "relative" so it stays within a box. This is my first time using HTML and Javascript together. The code just doesn't work (no errors or warnings). The random number generation code is as follows:

function rand(min, max, step) {
    var delta,
        range,
        rand;
    if (arguments.length < 2) {
        max = min;
        min = 0;
    }
    if (!step) {
        step = 1;
    }
    delta = max - min;
    range = delta / step;
    rand = Math.random();
    rand *= range;
    rand = Math.floor(rand);
    rand *= step;
    rand += min;
    return parseInt(rand);
}

The code for setting the "apples" position (in js):

function generateApple() {
    let y = parseInt(rand(-15, 470, 15))
    apple.style.top = y
    console.log(apple.style.top)
}

It does successfully print the new location but doesn't move the "apple" HTML object to the position. I have the initial position set to 15 in style.left and 15 in style.top. The CSS for the apple is as follows:

.apple {
    height: 15px;
    width: 15px;
    background-color: red;
    border: 2px;
}

The code that sets the position as relative when the window loads is as follows

window.addEventListener('load', () => {
    snake.style.position = 'relative';
    apple.style.position = 'relative'
    snake.style.left = 105;
    snake.style.top = 105;
    apple.style.top = 15;
    apple.style.left = 15;
    if (highScore == null) {
        window.localStorage.setItem('high_score', 0)
    }
});

The full code is on this website: https://passionproject.on.fleek.co

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Window load event is fired after the JavaScript that is positioning the apple has been run. If you put could breakpoints in your code, you will see that first it moves the apple into the right position and then the load event listener fires.

Since your JS is at the bottom of the page, the simplest fix really is to not use load event listener and just do it immediately.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda